package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.properties.WeChatProperties;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {


    @Autowired
    private WeChatProperties weChatProperties;
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN ";

    @Override
    public String getOpenid(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppId());
        paramMap.put("secret", weChatProperties.getAppSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        String result = HttpUtil.get(OPENID_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确，则获取不到openid，响应失败
        Integer errcode = jsonObject.getInt("errcode");
        if (ObjectUtil.isNotEmpty(errcode)) { //有问题
            log.error("获取openid失败,错误码{},错误信息{}", errcode, jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }


        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String code) {
        //获取access_token
        String accessToken = getAccessToken();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("code", code);

        String result = HttpUtil.post(PHONE_URL.replace("ACCESS_TOKEN", accessToken), JSONUtil.toJsonStr(codeMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);

        if (jsonObject.getInt("errcode") != 0) {
            log.error("获取手机号失败,错误码{},错误信息{}", jsonObject.getInt("errcode"), jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getAccessToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppId());
        paramMap.put("secret", weChatProperties.getAppSecret());
        paramMap.put("grant_type", "client_credential");

        String result = HttpUtil.get(ACCESS_TOKEN_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        return jsonObject.getStr("access_token");
    }
}
